<script setup>
import Toast from "@vant/weapp/dist/toast/toast";
import newLoading from '@/components/newLoading/index.vue';

import { getCategoryDetail } from "@/api/home";
import { editImgUpload, getImgSegmentation, getImageByTaskId } from '@/api/painting'
import { imgUploadVerify } from '@/utils/auth'


import { ref } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app'



// 类型列表
const typeList = ref([
  { id: 1, icon: 'ai-icon-renxiangchongwu', label: '人体人像', value: 'human' },
  { id: 2, icon: 'ai-icon-shangpin', label: '商品货物', value: 'product' },
  { id: 3, icon: 'ai-icon-suoyou', label: '通用', value: 'general' },
])

// 页面携带参数
const queryItem = ref({})
// 页面参数
const queryParams = ref({
  imageFileUrl: '',
})
// 查询详情信息
const queryInfo = ref({})
// 提交数据
const queryData = ref({
  model: 'DOUBAO',
})
// 算力消耗
const expendNum = ref(0)
// 算力消耗列表
const expendNumList = ref([])


// tabs选中
const tabCurrent = ref(0)


const loading = ref(false);
const loadingRef = ref(null);

let timer = null
const taskId = ref('')


// 开始生成
async function startFn() {
  clearInterval(timer);
  await verifyFn()
  loading.value = true
  await editImgUploadFn()
  getImgSegmentationFn()
}


// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    res.data.title = queryInfo.value.title
    uni.navigateTo({
      url: `/draw/imgMatting/detail/index?data=${JSON.stringify(res.data)}`
    })
  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1]
    Toast.fail(errorMessage);
    loading.value = false
  }
}


// 发型抠图任务提交
async function getImgSegmentationFn() {
  if (tabCurrent.value === 1) {
    queryData.value.type = queryParams.value.type
  } else {
    queryData.value.type = null
  }

  try {
    const res = await getImgSegmentation(queryData.value)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 5000);
  } catch (error) {
    loading.value = false
  }
}



// 上传原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await editImgUpload({
        type: 2,
        orgImg: queryParams.value.imageFileUrl
      })
      queryData.value.imageFileUrl = res.orgImgUrl
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}



function verifyFn() {
  return new Promise((resolve, reject) => {
    if (queryParams.value.imageFileUrl === '') {
      Toast.fail('请先选择图片')
      return false
    }
    resolve()
  })
}

// 类型选择
function typeItemClick(item) {
  queryParams.value.type = item.value
}

// 上传图片
async function uploadImgFn() {
  const res = await imgUploadVerify()
  queryParams.value.imageFileUrl = res
}


// 图片预览
function previewImageFn() {
  uni.previewImage({
    urls: [queryParams.value.imageFileUrl],
  });
}


// tabs切换
function tabsChange(index) {
  tabCurrent.value = index
  if (index === 0) {
    queryParams.value.type = ''
    expendNum.value = expendNumList.value[0]
  } else {
    queryParams.value.type = 'human'
    expendNum.value = expendNumList.value[1]
  }
}


// 数据转换
function dataConversion() {
  queryInfo.value.categoryParam.forEach(item => {
    if (item.title === 'expendNum') {
      expendNumList.value = item.data[0].title.split(',').sort((a, b) => a - b)
      expendNum.value = expendNumList.value[0]
    }
  })
}



// 获取分类详情
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id)
  queryInfo.value = res.data
  dataConversion()
}


// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}

onUnload(() => {
  clearInterval(timer);
  loading.value = false
})

onLoad((e) => {
  if (e.item) {
    queryItem.value = JSON.parse(e.item)
  }
  getCategoryDetailFn()
})

defineExpose({
  tabsChange,
  uploadImgFn
})
</script>

<template>
  <div class='imgMatting'>
    <NavBar>{{ queryInfo.title }}</NavBar>

    <div class="container">
      <div class="img_box">
        <!--上传按钮-->
        <div v-if="!queryParams.imageFileUrl" class="uploadImgBtn" @click="uploadImgFn">
          <i class="iconfont ai-icon-xiangcexuanze"></i>
          相册选择
        </div>
        <!--重新上传-->
        <div v-else class="upload_box" @click.stop="uploadImgFn">
          <i class="iconfont ai-icon-refresh"></i>
          重新上传
        </div>

        <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" alt="" class="imgSty" mode="aspectFit"
          @click="previewImageFn">
      </div>
    </div>
    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <div class="footer_top">
          <div class="tabs">
            <div class="tab" :class="{ active: tabCurrent === 0 }" @click="tabsChange(0)">智能抠图</div>
            <div class="tab" :class="{ active: tabCurrent === 1 }" @click="tabsChange(1)">手动选择</div>
          </div>
        </div>

        <div class="footer_center">
          <div class="type_list" v-if="tabCurrent === 1">
            <div class="type_item" :class="{ active: queryParams.type === item.value }" v-for="item of typeList"
              @click="typeItemClick(item)">
              <div class="icon_box">
                <i :class="`iconfont ${item.icon}`"></i>
              </div>
              <div class="text">{{ item?.label }}</div>
            </div>
          </div>

        </div>
        <div class="create_btn">
          <myDrawButton :expendNum="expendNum" @click="startFn">一键抠图</myDrawButton>
        </div>
      </div>
    </div>
  </div>
  <van-toast id="van-toast"></van-toast>
  <newLoading ref="loadingRef" v-model="loading" :duration="15000" :label="['排队中，预计等待10秒']" @close="loadingClose">
  </newLoading>
</template>

<style lang='scss' scoped>
.imgMatting {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .container {
    box-sizing: border-box;
    flex: 1;
    padding: 30rpx;
    display: flex;
    flex-direction: column;

    .img_box {
      flex: 1;
      border-radius: 20rpx;
      background-color: var(--a-main-box-bg-color);
      position: relative;

      .uploadImgBtn {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 228rpx;
        height: 84rpx;
        border-radius: 45rpx;
        background-color: transparent;
        border: 3rpx solid var(--a-main-color);
        color: var(--a-one-text-color);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10rpx;
      }

      .upload_box {
        position: absolute;
        bottom: 20rpx;
        right: 20rpx;

        width: 84rpx;
        height: 84rpx;

        font-size: 16rpx;
        color: var(--a-one-text-color);
        border-radius: 13rpx;
        background: rgba(0, 0, 0, 0.6);

        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 5rpx;


        .iconfont {
          font-size: 36rpx;
        }
      }

      .imgSty {
        width: 100%;
        height: 100%;
      }
    }
  }

  .footer {
    .footer_placeholder {
      height: 400rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 400rpx;
      background: var(--a-main-tabNav-bg-color);
      padding: 30rpx;

      .footer_top {
        position: relative;

        .uploadImg {
          position: absolute;
          left: 0;
          top: -10rpx;
          font-size: 20rpx;
          text-align: center;
          color: var(--a-two-text-color);
        }

        .tabs {
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          color: var(--a-three-text-color);
          font-weight: bold;
          font-size: 32rpx;

          .tab {
            &.active {
              color: var(--a-one-text-color);
            }
          }
        }
      }

      .footer_center {
        .type_list {
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          gap: 20rpx;
          margin-top: 30rpx;

          .type_item {
            box-sizing: border-box;
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10rpx;
            font-size: 22rpx;
            color: var(--a-two-text-color);

            &.active {
              color: var(--a-main-color);

              .icon_box {
                background: var(--a-main-color);
              }
            }

            .icon_box {
              width: 64rpx;
              height: 64rpx;
              background: var(--a-main-box-bg-color);
              border-radius: 10rpx;
              display: flex;
              align-items: center;
              justify-content: center;

              .iconfont {
                font-size: 34rpx;
                color: #FFF;
              }

            }


          }
        }
      }

      .create_btn {
        margin-top: 45rpx;
      }
    }
  }

}
</style>